package com.linkage.seapeak.adapter;

import android.arch.core.executor.TaskExecutor;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.bean.LoginInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.seapeak.activity.user.PersonalAddressActivity;
import com.linkage.seapeak.pojo.MessageItem;
import com.linkage.seapeak.utils.CommonUtils;
import com.seapeak.recyclebundle.BaseHolder;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.util.List;

import cn.bingoogolapple.swipeitemlayout.BGASwipeItemLayout;
import jp.wasabeef.glide.transformations.CropCircleTransformation;


public class ConversationAdapter extends BaseRecyclerAdapter<ConversationAdapter.ItemViewHolder> {

    Context context;
    List<MessageItem> mDataList;
    int type;
    String sendUserId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");
    Bitmap blueArrow;

    public ConversationAdapter(Context context, int type, List<MessageItem> mDataList) {
        this.context = context;
        this.type = type;
        this.mDataList = mDataList;

        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down_blue);
        Matrix m = new Matrix();
        final int width = bitmap.getWidth();
        final int height = bitmap.getHeight();
        if (width != CommonUtils.dp2px(context, 16) || height != CommonUtils.dp2px(context, 16)) {
            final float sx = CommonUtils.dp2px(context, 16) / (float) width;
            final float sy = CommonUtils.dp2px(context, 16) / (float) height;
            m.setScale(sx, sy);
        }
        m.postRotate(180);
        blueArrow = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);
    }

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        if (i == 1)
            return new ItemViewHolder(LayoutInflater.from(context).inflate(
                    R.layout.item_conversation_notice, viewGroup, false));
        else
            return new ItemViewHolder(LayoutInflater.from(context).inflate(
                    R.layout.item_conversation, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(final ItemViewHolder holder, final int position) {
        super.onBindViewHolder(holder, position);
        final MessageItem item = mDataList.get(position);
        LoginInfo targetUser = null;
        try {
            if (item.getFromUserId().equals(sendUserId))
                targetUser = item.getSendUser();
            else
                targetUser = item.getFromUser();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(targetUser == null) {
                targetUser = new LoginInfo();
                targetUser.setAvatar("");
                targetUser.setUsername("未知用户");
            }
        }

        if("system".equalsIgnoreCase(item.getSendUserId()) || item.getSendUser()==null)
        {
            Glide.with(context).load("")
                    .bitmapTransform(new CropCircleTransformation(context))
                    .placeholder(R.drawable.system_notice_blue)
                    .into(holder.avatar);
//            holder.avatar.setBackgroundResource(R.drawable.system_notice_blue);
        }else {

            Glide.with(context).load(targetUser.getAvatarUrl())
                    .bitmapTransform(new CropCircleTransformation(context))
                    .placeholder(R.drawable.logo)
                    .into(holder.avatar);
        }
        holder.detail.setText(item.getNote());
        if(type ==2 ) {
            holder.time.setText(CommonUtils.resetTime(item.getSendTime()));
        }else{
            holder.time.setText(item.getSendTime());
        }



        if (type == 1) {
            if(item.getProject() != null && !TextUtils.isEmpty(item.getProject().getProjectName())) {
                holder.name.setText("来自：" + item.getProject().getProjectName());
            }
            holder.detail.setTextColor(item.isStatus() ? 0xff888888 : 0xff333333);
            holder.itemView.findViewById(R.id.see_more).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    holder.detail.setMaxLines(100);
                    holder.itemView.findViewById(R.id.see_more).setVisibility(View.GONE);
                    holder.detail.setMovementMethod(LinkMovementMethod.getInstance());
                    String temp = " 收起 arrow";
                    ImageSpan imgSpan = new ImageSpan(context, blueArrow);
                    ClickableSpan clickableSpan = new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            holder.detail.setMaxLines(2);
                            holder.detail.setText(item.getNote());
                            holder.itemView.findViewById(R.id.see_more).setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            //设置指定区域的文字变蓝色
                            ds.setColor(0xff1E72F9);
                            //设置指定区域的文字有下划线
                            ds.setUnderlineText(false);
                        }
                    };
                    SpannableString spannableString = new SpannableString(temp);
                    spannableString.setSpan(imgSpan, 4, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableString.setSpan(clickableSpan, 1, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    holder.detail.append(spannableString);
                }
            });
            holder.itemView.post(new Runnable() {
                @Override
                public void run() {
                    holder.itemView.findViewById(R.id.see_more).setVisibility(View.GONE);
//                    holder.itemView.findViewById(R.id.see_more).setVisibility(
//                            holder.detail.getLineCount() > 2 ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            holder.name.setText(targetUser.getUsername());
            if(item.getProject() != null && !TextUtils.isEmpty(item.getProject().getProjectName())) {
                holder.company.setText("来自：" + item.getProject().getProjectName());
            }
//            if (targetUser.getCompany() != null && !"".equalsIgnoreCase(targetUser.getCompany()) && !"null".equalsIgnoreCase(targetUser.getCompany())) {
//                holder.company.setText("来自：" + targetUser.getCompany());
//            }
            holder.detail.setTextColor(0xff444444);
        }


        holder.etItemBgaswipeRead.setVisibility(item.isStatus() ? View.GONE : View.VISIBLE);

        if(type ==2)
        {
            holder.unreadCount.setVisibility(View.GONE);
            if(item.getUnreadCount()!=null && !"0".equalsIgnoreCase(item.getUnreadCount()) && !"".equalsIgnoreCase(item.getUnreadCount())) {
                holder.unreadCount1.setText("  "+item.getUnreadCount()+"  ");
            }
            holder.unreadCount1.setVisibility(item.isStatus() ? View.GONE : View.VISIBLE);
        }else {
            if( holder.unreadCount1!=null) {
                holder.unreadCount1.setVisibility(View.GONE);
            }
            holder.unreadCount.setVisibility(item.isStatus() ? View.GONE : View.VISIBLE);
        }
        holder.etItemBgaswipeRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                holder.silItemBgaswipeRoot.closeWithAnim();
                onItemClickListener.onItemClick(v, position, holder);
            }
        });
        holder.tvItemBgaswipeDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                holder.silItemBgaswipeRoot.closeWithAnim();
                onItemClickListener.onItemClick(v, position, holder);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDataList == null ? 0 : mDataList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return type;
    }

    class ItemViewHolder extends BaseHolder {

        public BGASwipeItemLayout silItemBgaswipeRoot;
        public View unreadCount;
        public TextView unreadCount1;
        public TextView etItemBgaswipeRead;
        public TextView tvItemBgaswipeDelete;
        public ImageView avatar;
        public TextView detail;
        public TextView company;
        public TextView name;
        public TextView time;

        public ItemViewHolder(View view) {
            super(view);
            silItemBgaswipeRoot = (BGASwipeItemLayout) view.findViewById(R.id.sil_item_bgaswipe_root);
            unreadCount = (View) view.findViewById(R.id.unread_count);
            etItemBgaswipeRead = (TextView) view.findViewById(R.id.et_item_bgaswipe_read);
            tvItemBgaswipeDelete = (TextView) view.findViewById(R.id.tv_item_bgaswipe_delete);
            avatar = (ImageView) view.findViewById(R.id.avatar);
            detail = (TextView) view.findViewById(R.id.detail);
            company = (TextView) view.findViewById(R.id.company);
            name = (TextView) view.findViewById(R.id.name);
            time = (TextView) view.findViewById(R.id.time);
            unreadCount1 = (TextView)view.findViewById(R.id.unread_count1);
        }
    }

}